﻿using MediatR;
using PublicCommon;
using T_Material.Domain;
using T_Material.Infrastructure.Interface;
using T_Material.Read.API.Application.Commands.PurchaseCommand;

namespace T_Material.Read.API.Application.CommandHandlers.PurchaseHandler
{
    public class PurchaseListStateCommandHandler : IRequestHandler<PurchaseListStateCommand, PageResult<Purchase>>
    {
        private readonly IPurchaseRepository purchaseRepository;

        public PurchaseListStateCommandHandler(IPurchaseRepository purchaseRepository)
        {
            this.purchaseRepository = purchaseRepository;
        }
        public async Task<PageResult<Purchase>> Handle(PurchaseListStateCommand request, CancellationToken cancellationToken)
        {
            var list = purchaseRepository.GetList().Result.Where(x => !x.IsDel&&x.AuditState!=0).AsQueryable();
            if (!string.IsNullOrEmpty(request.GoodsName))
            {
                list = list.Where(x => x.GoodsName.Contains(request.GoodsName));
            }
            if (!string.IsNullOrEmpty(request.Applicant))
            {
                list = list.Where(x => x.Applicant.Contains(request.Applicant));
            }
            if (!string.IsNullOrEmpty(request.MateriaQluality))
            {
                list = list.Where(x => x.MateriaQluality.Contains(request.MateriaQluality));
            }
            if (!string.IsNullOrEmpty(request.Country))
            {
                list = list.Where(x => x.Country.Contains(request.Country));
            }
            if (request.AuditState == 0)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            else if (request.AuditState == 1)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            else if (request.AuditState == 2)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }
            else if (request.AuditState == 3)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Purchase>
            {
                List = pagelist,
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
